package com.briup.jd2407cms.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.briup.jd2407cms.domain.Category;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: cms2
 * @BelongsPackage: com.briup.jd2407cms.utils
 * @Author: wangjie
 * @CreateTime: 2024-11-22  16:55
 * @Description: TODO
 * @Version: 1.0
 */
public class CategoryListener extends AnalysisEventListener<Category> {
    List<String> names = new ArrayList<>();
    @Override
    public void invoke(Category category, AnalysisContext context) {
        String name = category.getName();
        if (!StringUtils.hasText(name)){
            throw new RuntimeException(String.format("第%s行名称为 空，请核实", context.readRowHolder().getRowIndex() + 1));
        }
        if (names.contains(name)){
            throw new RuntimeException(String.format("第%s行名称已 重复，请核实", context.readRowHolder().getRowIndex() + 1));
        }else {
            names.add(name);
        }

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException){
            //从0开始计算
            int columnIndex = ((ExcelDataConvertException)
                    exception).getColumnIndex() + 1;
            int rowIndex = ((ExcelDataConvertException)
                    exception).getRowIndex() + 1;
            String message = "第" + rowIndex + "行，第" +
                    columnIndex + "列" + "数据格式有误，请核实";
            exception.printStackTrace();
            throw new RuntimeException(message);
        } else if (exception instanceof RuntimeException) {
            throw exception;
        } else {
            super.onException(exception, context);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        names.clear();
    }
}
